package com.cjx.stars.aop;

import cn.hutool.bloomfilter.BloomFilter;
import com.cjx.stars.common.MyException;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.cjx.stars.constant.BloomFilterConstants.*;
import static com.cjx.stars.constant.FailMessage.*;

/**
 * @author cjx
 * @description 查询其元素时先被布隆过滤器过滤一篇
 * @createDate 2024/4/23 20:38
 **/
@Aspect
@Log4j2
@Component
@ConditionalOnProperty(prefix = "stars", name = "enable-bloom-filter", havingValue = "true")
public class SearchBloomFilterAop {

    @Resource
    private BloomFilter bloomFilter;

    /**
     * 查询用户
     * @param joinPoint 切面点信息
     */
    @Before("execution(* com.cjx.stars.service.impl.UserServiceImpl.getUserById(..))")
    public void searchUser(JoinPoint joinPoint){
        Object userId = joinPoint.getArgs()[0];
        boolean contains = bloomFilter.contains(USER_BLOOM_PREFIX + userId);
        if (!contains) {
        log.info("用户 {} 不存在布隆过滤器中",userId);
            throw new MyException(THE_USER_DOES_NOT_EXIST);
        }
        log.info("用户 {} 存在布隆过滤器中",userId);

    }

    /**
     * 查询团队
     * @param joinPoint 切面点信息
     */
    @Before("execution(* com.cjx.stars.service.impl.TeamServiceImpl.getTeamById(..))")
    public void searchTeam(JoinPoint joinPoint){
        Object teamId = joinPoint.getArgs()[0];
        boolean contains = bloomFilter.contains(TEAM_BLOOM_PREFIX + teamId);
        if (!contains) {
            log.info("团队 {} 不存在布隆过滤器中",teamId);
            throw new MyException(ERROR_THE_TEAM_DOES_NOT_EXIST);
        }
        log.info("用户 {} 存在布隆过滤器中",teamId);
    }

    /**
     * 查询博文
     * @param joinPoint 切面点信息
     */
    @Before("execution(* com.cjx.stars.service.impl.BlogServiceImpl.getBlogById(..))")
    public void searchBlog(JoinPoint joinPoint){
        Object blogId = joinPoint.getArgs()[0];
        boolean contains = bloomFilter.contains(BLOG_BLOOM_PREFIX + blogId);
        if (!contains) {
            log.info("博文 {} 不存在布隆过滤器中",blogId);
            throw new MyException(NOT_THE_BLOG);
        }
    }

}
